"""@package dfa


"""

import core, random

class Simulator:
	dfa = None
	init_state = None
	current_state = None

	def __init__(self, dfa):
		self.dfa = dfa
		self.init_state = dfa.init_state

	def step(self, word):
		self.current_state = self.init_state
		word = list(word)
		output = []
		for w in word:
			trans = self.current_state.transitions[w]
			self.current_state = trans.end
			output.append(trans._out)
		return "".join(output)
	
	def cycle(self, word):
		count = 0
		out = word
		while out != word or count == 0:
#			print out
			out = self.step(out)
			count += 1
		return count
	
	def max_cycle(self, bits):
		set = {}
		for i in xrange(2 ** bits):
			set[self.tobin(i, bits)] = 0

		max_cycle = 0
		max_string = ""
		while len(set) > 0:
			word = set.keys()[0]
			count = 0
			out = word
			while out != word or count == 0:
				del set[out]
				out = self.step(out)
				count += 1
			if count > max_cycle:
				max_cycle = count
				max_string = word
		return (max_cycle, max_string)

	def print_cycle_func(self):
		"""
		Prints out the cycle length of a random word on
		i bits, where i keeps increasing until quit
		"""
		i = 1
		while True:
			list = []
			for j in range(i):
				list.append(str(random.randint(0, 1)))
			word = "".join(list)
			print "(%d, %d)" % (i, self.cycle(word))
			i += 1

	def tobin(self, x, count=8):
		"""
		Integer to binary
		Count is number of bits
		"""
		return "".join(map(lambda y:str((x>>y)&1), \
			range(count-1, -1, -1)))
